package com.zhongge.binarytreeOJ;

/**
 * @ClassName MyBinTree
 * @Description TODO
 * @Author zhongge
 * @Date 2025/9/1 22:06
 * @Version 1.0
 */
public class MyBinTree {

    public static class TreeNode{
        public char val;
        public TreeNode left;

        public TreeNode(char val) {
            this.val = val;
        }

        public TreeNode right;

    }

    /**
     * 根据前序遍历创建 二叉树
     * @param s 前序遍历字符串
     * @return 根节点
     */
    public TreeNode createOfPreOrder(String s) {
        int[] index = new int[1];
        return createNode(s, index);
    }
    //辅助函数
    private TreeNode createNode(String s, int[] index) {
        //处理基本出口
        if (index[0] >= s.length()) {
            return null;
        }
        //首先取出第一个元素 每一次取出后都截断这个字符

        char ch = s.charAt(index[0]);
        index[0]++;

        //递归出口
        if (ch == '#') {
            return null;
        }
        //递归剪枝：无
        //递归核心代码
        TreeNode root = new TreeNode(ch);

        //递归的递
        root.left = createNode(s, index);
        root.right = createNode(s, index);
        //递归的归
        return root;
    }

    /**
     * 递归实现 中序遍历
     * @param root 根节点
     */
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }



    public static void main(String[] args) {
        MyBinTree tree = new MyBinTree();
        TreeNode root = tree.createOfPreOrder("abc##de#g##f###");
        tree.inOrder(root);
    }

}
